<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="hAdd(1, '0')"
          >添加权限</el-button>
        </div>
        <el-table border :data="list" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.type === 1"
                type="text"
                @click="hAdd(2, scope.row.id)"
              >添加</el-button>
              <el-button
                type="text"
                @click="hEdit(scope.row.id)"
              >编辑</el-button>
              <el-button
                v-if="scope.row.children.length === 0"
                type="text"
                @click="hdel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :visible.sync="showDialog"
      :title="isEdit ? '编辑权限' : '添加权限'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="resetForm"
    >
      <!-- 表单内容 -->
      <el-form
        ref="refFormData"
        label-width="100px"
        :model="formData"
        :rules="rulesFormData"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPermissionList,
  addPermission,
  delPermission,
  updatePermission,
  getPermissionDetail
} from '@/api/permisson'
import { tranListToTreeData } from '@/utils/index'
export default {
  data() {
    const rulesFormDataName = (rules, value, callback) => {
      //   console.log(rules, value)
      let nameList = this.arr
        .filter((item) => item.pid === this.formData.pid)
        .map((item) => item.name)
      if (this.isEdit) {
        nameList = this.arr
          .filter(
            (item) =>
              item.pid === this.formData.pid && item.id !== this.formData.id
          )
          .map((item) => item.name)
      }
      console.log(nameList, value)
      if (nameList.includes(value)) {
        callback(new Error('名称有重复'))
      } else {
        callback()
      }
    }
    const rulesFormDataCode = (rules, value, callback) => {
      //   console.log(rules, value)
      let codeList = this.arr.map((item) => item.code)
      if (this.isEdit) {
        codeList = this.arr
          .filter((item) => item.id !== this.formData.id)
          .map((item) => item.code)
      }
      console.log(codeList)
      if (codeList.includes(value)) {
        callback(new Error('权限标识有重复'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      arr: [], // 验证数据
      showDialog: false, // 是否显示弹层
      isEdit: false, // 是否为编辑和添加
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rulesFormData: {
        name: [
          { required: true, message: '名字不能为空！', trigger: 'blur' },
          { validator: rulesFormDataName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空！', trigger: 'blur' },
          { validator: rulesFormDataCode, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述不能为空！', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getPermissionlist()
  },
  methods: {
    // 关闭弹窗重置表单
    resetForm() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.refFormData.resetFields()
    },
    async getPermissionlist() {
      const res = await getPermissionList()
      this.arr = res.data
      this.list = tranListToTreeData(res.data)
      console.log(this.list)
    },
    // 点击添加权限显示弹窗
    hAdd(type, pid) {
      this.showDialog = true
      this.isEdit = false
      this.formData.pid = pid
      this.formData.type = type
    },
    // 点击弹窗确认按钮
    hSubmit() {
      this.$refs.refFormData.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 实施添加功能
    async doAdd() {
      const res = await addPermission(this.formData)
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionlist()
    },
    // 删除权限点
    hdel(id) {
      this.$confirm('此操作将永久删除，是否继续？', '提示')
        .then(async() => {
          try {
            const res = await delPermission(id)
            this.$message.success(res.message)
            this.getPermissionlist()
          } catch (error) {
            console.dir(error)
            this.$message.warning(error)
          }
        })
        .catch(() => {})
    },
    // 编辑弹窗
    async hEdit(id) {
      const res = await getPermissionDetail(id)
      this.formData = res.data
      this.showDialog = true
      this.isEdit = true
    },
    // 编辑功能
    async doEdit() {
      try {
        await updatePermission(this.formData)
        this.getPermissionlist()
        this.$message.success('修改成功')
        this.showDialog = false
      } catch (error) {
        console.dir(error)
        this.$message.warning(error)
      }
    }
  }
}
</script>
